//
//  ThirdViewController.m
//  HGY
//
//  Created by lanou3g on 15/10/27.
//  Copyright (c) 2015年 顾成辉. All rights reserved.
//

#import "ThirdViewController.h"


@interface ThirdViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UICollectionView *collectionView;

@property(nonatomic,retain)NSMutableArray *dataArray;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UIImageView *imageView;

@end

@implementation ThirdViewController




- (void)viewDidLoad {
    [super viewDidLoad];
    
    

    
    [self requestDataForReloadWithUrl:@"http://baobab.wandoujia.com/api/v1/videos?start=10&num=10&categoryName=%E5%BC%80%E8%83%83&strategy=date&udid=d74ecfa50ec94615a2c4483236c9cd58bfa62b44&vc=48&vn=1.5.1&deviceModel=SM-G9009W&first_channel=eyepetizer_PP_market&last_channel=eyepetizer_PP_market" Block:^(NSArray *array) {
        self.dataArray = (NSMutableArray *)array;
        
        
        [self.collectionView reloadData];
        
        
    }];

    
    [self addCollectionView];
 
    
}

- (void)addCollectionView
{
    

    
    HJCarouselViewLayout *layout = [[HJCarouselViewLayout alloc] initWithAnim:HJCarouselAnimRotary];


    
    layout.itemSize = CGSizeMake(280 *kWidth, 280 *kHeight);
    

    self.collectionView = [[UICollectionView alloc] initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:layout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.showsVerticalScrollIndicator = NO;
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"ThirdCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"MyCell"];
    [self.view addSubview:self.collectionView];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    
}

- (NSIndexPath *)curIndexPath {
    // 获取一组当前显示的cell的indexPath的数组
    NSArray *indexPaths = [self.collectionView indexPathsForVisibleItems];
    NSIndexPath *curIndexPath = nil;
    NSInteger curzIndex = 0;
    for (NSIndexPath *path in indexPaths.objectEnumerator) {
        // 生成空白的attributes对象,其中只记录了类型是cell以及对应的位置是indesPath
        UICollectionViewLayoutAttributes *attributes = [self.collectionView layoutAttributesForItemAtIndexPath:path];
        // 设置页码
        if (!curIndexPath) {
            curIndexPath = path;
            curzIndex = attributes.zIndex;
            continue;
        }
        if (attributes.zIndex > curzIndex) {
            
            curIndexPath = path;
            curzIndex = attributes.zIndex;
        }
    }
    return curIndexPath;
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSIndexPath *curIndexPath = [self curIndexPath];
    if (indexPath.row == curIndexPath.row) {
        return YES;
    }
    // 通过动画滚动到下一个位置
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
    return NO;
}

//- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
//    NSLog(@" %ld", indexPath.row);
//}


#pragma mark <UICollectionViewDataSource>

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.dataArray.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    
     ThirdCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyCell" forIndexPath:indexPath];
    
    
    

  
    
    
    ThirdModel *model = self.dataArray[indexPath.row];
    
    
     self.collectionView.backgroundColor = [UIColor brownColor];
    

    

    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.coverForDetail] placeholderImage:[UIImage imageNamed:@"nowplaying_section_bg@2x"]];


    
    
    
 
    
//    cell.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%ld.jpg", indexPath.row % 3]];
    
    
    
    return cell;
}


#pragma mark -- 数据请求
- (void)requestDataForReloadWithUrl:(NSString *)url Block:(void(^)(NSMutableArray *array))block
{
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:30.0];
        [request setHTTPMethod:@"GET"];
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
        
        
        NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
        
       
        
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler: ^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            
            if (!data) {
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络不好,请求失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert self];
              
                return;
            }

       

          NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];

            
            NSMutableArray *array = dic[@"videoList"];
            
            self.dataArray = [NSMutableArray array];
            for (NSDictionary *dic1 in array) {
                ThirdModel *Model = [[ThirdModel alloc] init];
                [Model setValuesForKeysWithDictionary:dic1];
                [self.dataArray addObject:Model];
                
                
            }
            

            
            
            dispatch_async(dispatch_get_main_queue(), ^{
                block(self.dataArray);
                
            });
            


        }];

        
        [dataTask resume];
    });

                                      

}



- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    
    UIViewController *vc = [[UIViewController alloc]init];
    vc.view.backgroundColor = [UIColor yellowColor];
    
    VideoViewController *videoVC = [[VideoViewController alloc]init];
    
    ThirdModel *model = [[ThirdModel alloc]init];
    
    model = self.dataArray[indexPath.row];
    
    videoVC.thirdmodel = model;
    
    
    videoVC.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:videoVC animated:YES];
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
